﻿using Sidvall.Collections;
using Sidvall.LogManager.Net.Services.V1;
using Sidvall.Security;
using System.Threading.Tasks;

namespace Sidvall.LogManager
{
    public class ServerManager
    {
        #region Public Members

        public ServerContent ServerContent { get; private set; }
        protected System.Collections.Generic.Dictionary<long, LogScope> LogScopeIndex { get; private set; }

        #region InitializeAsync

        public async Task InitializeAsync(int? serverConnectionId)
        {
            var tasks = new System.Collections.Generic.List<System.Threading.Tasks.Task>();
            tasks.Add(LoadLogScopeIndexAsync(serverConnectionId));
            tasks.Add(LoadServerContentAsync(serverConnectionId));
            await System.Threading.Tasks.Task.WhenAll(tasks).ConfigureAwait(false);
        }

        #endregion

        #endregion
        #region Private Members

        #region LoadLogScopeIndexAsync

        private async Task LoadLogScopeIndexAsync(int? serverConnectionId)
        {
            var criteria = new Sidvall.Data.FetchListCriteria<Data.Fields.LogScopeField, Data.Relations.LogScopeRelation>();
            ParameterManager.InitializeParameters(criteria, serverConnectionId);
            var items = await Sidvall.LogManager.SystemContext.Current.DataPortal.LogScopeManager.GetItemsAsync(criteria).ConfigureAwait(false);
            this.LogScopeIndex = items.Items.ToDictionary(o => o.LogScopeId.Value, true);
        }

        #endregion
        #region LoadServerContentAsync

        private async Task LoadServerContentAsync(int? serverConnectionId)
        {
            this.ServerContent = await Sidvall.LogManager.SystemContext.Current.GetServerContentAsync(serverConnectionId).ConfigureAwait(false);
        }

        #endregion

        #endregion
        #region Constructors

        public ServerManager()
        {
        }

        #endregion
    }
}
